import { console } from "inspector";
import { userService } from "../../../services/user.service.js";

import { NotFoundError, BadRequestError } from "../../../utils/errors.js";

/**
 * Admin 用户管理控制器
 */
export class AdminUserController {
  /**
   * 获取用户列表
   */
  static async getUsersList(req, res) {
    const { page, limit, search, status, role, sortBy, order } =
      req.validatedData;
    const { data, pagination } = await userService.getUserList({
      page,
      limit,
      filters: { search, status, role },
      sort: { field: sortBy, order },
      isAdmin: true,
    });

    res.json({
      code: 200,
      success: true,
      data: { users: data, pagination: pagination },
    });
  }

  /**
   * 获取当前登录用户信息
   */
  static async getCurrentUser(req, res, err) {
    console.log("错误信息", err);
    try {
      console.log("获取当前登录用户信息");

      // 检查用户是否存在（req.user是否被认证中间件设置）
      if (!req.user) {
        console.log("用户未认证或登录信息已过期");
        throw new UnauthorizedError("用户未认证或登录信息已过期");
        return res.status(401).json({
          code: 401,
          success: false,
          message: "用户未认证或登录信息已过期",
        });
      }

      // 成功返回用户信息
      res.json({
        code: 200,
        success: true,
        data: {
          user: req.user, // 从认证中间件获取
        },
      });
    } catch (error) {
      console.error("获取用户信息时出错:", error);
      throw error;
      res.status(500).json({
        code: 500,
        success: false,
        message: "服务器内部错误，获取用户信息失败",
      });
    }
  }
  /**
   * 获取单个用户详情
   */
  static async getUserInfo(req, res) {
    const userId = req.user.id; // 从认证中间件获取
    console.log("当前用户ID:", userId);

    const user = await userService.getUserById(userId, true); // true表示获取完整信息
    console.log("获取的用户信息:", user);
    if (!user) {
      throw new NotFoundError("用户不存在");
    }

    res.status(200).json({
      code: 200,
      success: true,
      data: user,
    });
  }

  /**
   * 创建用户
   */
  static async createUser(req, res) {
    const userData = req.validatedData;
    if (!userData) {
      throw new BadRequestError("用户数据不能为空");
    }
    const { username, email, role, phone } = userData;
    // --检查必填字段
    if (!username || !role) {
      throw new BadRequestError("用户名、邮箱、角色是必填字段");
    }
    // 检查用户名/邮箱是否已存在
    const exists = await userService.checkUserExists(username, email, phone);
    if (exists) {
      throw new BadRequestError("用户名或邮箱已被注册");
    }
    // --创建新用户的时候初始化一个密码,后续再改进
    userData.password = "666666";
    const user = await userService.createUser(userData);
    res.status(200).json({
      code: 200,
      success: true,
      data: user,
      message: "用户创建成功",
    });
  }

  /**
   * 更新用户信息
   */
  static async updateUser(req, res) {
    const { id } = req.params;
    const updateData = req.validatedData;
    const user = await userService.updateUser(id, updateData);

    if (!user) {
      throw new NotFoundError("用户不存在");
    }

    res.json({
      code:200,
      success: true,
      data: user,
      message: "用户信息更新成功",
    });
  }
  /**
   * 批量删除用户
   */
  static async batchDeleteUsers(req, res) {
    console.log("批量删除用户");
    console.log(req.validatedData);
   // 防御性检查
    if (!req.validatedData?.ids) {
      throw new BadRequestError("请求数据格式异常");
    }
    // 类型转换 (MySQL整数ID场景)
    const ids = req.validatedData.ids.map(id => 
      typeof id === 'string' && /^\d+$/.test(id) ? Number(id) : id
    );
    if (!Array.isArray(ids) || ids.length === 0) {
      throw new BadRequestError("请提供有效的用户ID列表");
    }

    const result = await userService.batchDeleteUsers(ids);

    if (result.length === 0) {
      throw new NotFoundError("没有找到要删除的用户");
    }

    res.json({
      code: 200,
      success: true,
      message: "批量删除用户成功",
      data: result,
    });
  }
  /**
   * 重置用户密码
   */
  static async resetPassword(req, res) {
    const { id } = req.params;
    const { newPassword } = req.validatedData;

    await userService.resetPassword(id, newPassword);

    res.json({
      success: true,
      message: "密码重置成功",
    });
  }

  /**
   * 删除用户 (软删除)
   */
  static async deleteUser(req, res) {
    const { id } = req.params;

    const result = await userService.softDeleteUser(id);

    if (!result) {
      throw new NotFoundError("用户不存在");
    }

    res.json({
      success: true,
      message: "用户已标记为删除",
    });
  }

  /**
   * 恢复已删除用户
   */
  static async restoreUser(req, res) {
    const { id } = req.params;

    const user = await userService.restoreUser(id);

    if (!user) {
      throw new NotFoundError("用户不存在或未被删除");
    }

    res.json({
      success: true,
      data: user,
      message: "用户恢复成功",
    });
  }
}
